package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @Author: xrl
 * @Date: 2022/10/21  14:35
 * @Version 1.0
 */

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    /**
     * 添加任务到延迟队列中
     *
     * @param wmNews
     */
    @Override
    public void addWmNewsToTask(WmNews wmNews) {
        log.info("添加任务到延迟服务中----begin");
        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews news = new WmNews();
        news.setId(wmNews.getId());

        //序列化传输对象
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        //添加任务
        scheduleClient.addTask(task);

        log.info("添加任务到延迟服务中----end");
    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 消费延迟队列数据
     */
    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewsByTask() {
        ResponseResult result = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType()
                , TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (result.getCode().equals(200) && result.getData() != null) {
            String json = JSON.toJSONString(result.getData());
            //转换为java对象
            Task task = JSON.parseObject(json, Task.class);
            //反序列化
            byte[] bytes = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(bytes, WmNews.class);
            //调用文章审核接口
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }
        log.info("文章审核---消费任务执行---完成---");
    }
}
